<?php

namespace App\Models\Traits;

use App\Models\Application;
use Dcat\Admin\Admin;
use Dcat\Admin\Models\Administrator;
use Illuminate\Database\Eloquent\Builder;

trait BelongsToApplication
{
    static function bootBelongsToApplication(): void
    {
        self::creating(function ($model) {
            $model->setAdmin();
        });
    }

    public function setAdmin(): void
    {
        if (Admin::user()) {
            $this->admin = Admin::user();
        }
    }

    public function application()
    {
        return $this->belongsTo(Application::class);
    }

    public function scopeOfAdmin(Builder $query): void
    {
        if (!Admin::user()->isAdministrator()) {
            $query->whereHas('application', function (Builder $builder) {
                $builder->where('admin_id', Admin::user()->getKey())
                    ->where('status', 1)
                    ->where('expired_at', '>', now());
            });
        } else {
            $query->with('application');
        }
    }

    public function setAdminAttribute(Administrator $admin): void
    {
        if (!isset($this->attributes['application_id'])) {
            $this->attributes['application_id'] = Application::where('admin_id', $admin->getKey())->value('id');
        }
    }
}
